package com.bawei.bydayzg_two.fragment

import android.content.Context
import android.os.Bundle
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.launcher.ARouter
import com.bawei.base.mvvm.BaseFragment
import com.bawei.bydayzg_two.R
import com.bawei.bydayzg_two.adapter.CouponsAdapter
import com.bawei.bydayzg_two.adapter.GoodsAdapter
import com.bawei.bydayzg_two.adapter.MenuAdapter
import com.bawei.bydayzg_two.adapter.TypeAdapter
import com.bawei.bydayzg_two.databinding.FragmentHomeBinding
import com.bawei.bydayzg_two.viewModel.HomeViewModel
import com.blankj.utilcode.util.ToastUtils
import com.bumptech.glide.Glide
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener
import com.youth.banner.BannerConfig
import com.youth.banner.loader.ImageLoader

class HomeFragment : BaseFragment<FragmentHomeBinding,HomeViewModel>() {
    var list:ArrayList<String> = arrayListOf()//存放图片的地址
    lateinit var menuAdapter: MenuAdapter
    lateinit var couponsAdapter: CouponsAdapter
    lateinit var typeAdapter: TypeAdapter
    lateinit var goodsAdapter: GoodsAdapter
    var pageNum = 1
    var pageType = 4//数据分类默认为4
    //
    override fun getLoutyId(): Int {
        return R.layout.fragment_home
    }

    override fun getViewModel(): Class<HomeViewModel> {
        return HomeViewModel::class.java
    }

    override fun initView() {

        //请求数据
        viewModel.index()

        //首月菜单
        menuAdapter = MenuAdapter()
        binding.rvMenu.adapter = menuAdapter
        binding.rvMenu.layoutManager = GridLayoutManager(requireActivity(),5)
        //StaggeredGridLayoutManager(2,StaggeredGridLayoutManager.VERTICAL)
        //点击跳转到查询页面
        binding.llSearch.setOnClickListener {
            ARouter.getInstance().build("/app/SearchActivity").navigation()
        }

        //优惠卷
        couponsAdapter = CouponsAdapter()
        binding.rvCoupon.adapter = couponsAdapter
        binding.rvCoupon.layoutManager = LinearLayoutManager(requireActivity(),LinearLayoutManager.HORIZONTAL,false)
        //
        viewModel.coupons("10","1","1")
        
        //点击优惠卷进行领取
        couponsAdapter.setOnItemClickListener { adapter, view, position -> 
            //只有未领取的优惠卷可以领取
            if (!couponsAdapter.data[position].isUse){
                viewModel.couponsGet(couponsAdapter.data[position].id)
                //领取成功
                (couponsAdapter.getViewByPosition(position,R.id.coupons_get) as TextView).text = "已领取"
                //
                couponsAdapter.data[position].isUse = true
            } else {
                ToastUtils.showLong("已领取,不能重复领取")
            }
        }

        //分类
        typeAdapter = TypeAdapter()
        binding.rvType.adapter = typeAdapter
        binding.rvType.layoutManager = GridLayoutManager(context,4)
        //

        //商品列表
        goodsAdapter = GoodsAdapter()
        binding.rvGoods.adapter = goodsAdapter
        binding.rvGoods.layoutManager = GridLayoutManager(context,2)
        //
        viewModel.indexGoods(pageType,5,pageNum)

        //点击下方的商品数据发生变化
        typeAdapter.setOnItemClickListener { adapter, view, position ->
            pageType = typeAdapter.data[position].type.toInt()
            pageNum = 1
            //
            typeAdapter.getIndex(pageType)
            //刷新数据
            viewModel.indexGoods(pageType,5,pageNum)
        }

        //刷新，加载更多
        binding.sm.setOnRefreshLoadMoreListener(object :OnRefreshLoadMoreListener{
            override fun onRefresh(refreshLayout: RefreshLayout) {
                pageNum = 1//刷新永远从第一页开始
                //
                viewModel.indexGoods(pageType,5,pageNum)
                //
                binding.sm.finishRefresh()
            }

            override fun onLoadMore(refreshLayout: RefreshLayout) {
                pageNum ++
                //
                viewModel.indexGoods(pageType,5,pageNum)
                //
                binding.sm.finishLoadMore()
            }
        })

        //点击商品列表跳转详情--0827
        goodsAdapter.setOnItemClickListener { adapter, view, position ->
            ARouter.getInstance().build("/app/DetailActivity2")
                .withInt("goodsId",goodsAdapter.data[position].id).navigation()
        }

        //点击分类跳转到新的分类界面
        menuAdapter.setOnItemClickListener { adapter, view, position ->
            when(position){
                    0->ARouter.getInstance().build("/app/CateActivity").navigation()
            }
        }

    }

    override fun initDate() {

        //轮播图---------1
        viewModel.indexSuccess.observe(this){
            if (it.code == 200){
                //显示轮播图
                it.data.banner.forEach {
                    list.add(it.pic)
                }
                //轮播图
                binding.banner.setImages(list)
                    .setImageLoader(object :ImageLoader(){
                        override fun displayImage(
                            context: Context?,
                            path: Any?,
                            imageView: ImageView?
                        ) {
                            if ( context != null && imageView != null){
                                Glide.with(context).load(path).into(imageView)
                            }
                        }
                    }).setDelayTime(2000)
                    .setOnBannerListener { //点击事件
                        ToastUtils.showLong("点击了第${it+1}张图片")
                    }
                    //设置轮播图样式
                    .setBannerStyle(BannerConfig.NUM_INDICATOR)
                    .start()//设置轮播时长

                //加载菜单
                menuAdapter.data.clear()
                menuAdapter.data.addAll(it.data.menus)
                menuAdapter.notifyDataSetChanged()
                //加载分类
                typeAdapter.data.clear()
                typeAdapter.data.addAll(it.data.explosiveMoney)
                typeAdapter.notifyDataSetChanged()
            }
            ToastUtils.showLong(it.message)
        }
        //失败
        viewModel.indexFail.observe(this){
            ToastUtils.showLong(it)
        }

        //优惠卷
        viewModel.couponsSuccess.observe(this){
            if (it.code == 200){
                couponsAdapter.data.clear()
                couponsAdapter.data.addAll(it.data)
                couponsAdapter.notifyDataSetChanged()
                //
                Log.e("TAG", "优惠卷成功返回数据: "+it.data )
            }
        }
        //失败
        viewModel.couponsFail.observe(this){
            ToastUtils.showLong(it)
            //
            Log.e("TAG", "优惠卷失败: "+it)
        }

        //商品
        viewModel.indexGoodsSuccess.observe(this){
            if (it.code == 200){
                //当页面为一时，要么是初始化，要么是刷新的结果
                if (pageNum == 1){
                    goodsAdapter.data.clear()
                }
                goodsAdapter.data.addAll(it.data.list)
                goodsAdapter.notifyDataSetChanged()
                //没有数据时给出提示
                if (it.data.list.size == 0){
                    ToastUtils.showLong("没有更多数据了")
                }
            }
            ToastUtils.showLong(it.message)
        }
        //失败
        viewModel.indexGoodsFail.observe( this){
            ToastUtils.showLong(it)
        }

        //领取优惠卷的结果
        viewModel.couponsGetSuccess.observe(this){
            ToastUtils.showLong(it.message)
        }
        //失败
        viewModel.couponsGetFail.observe(this){
            ToastUtils.showLong(it)
        }
    }

}